const path = require('path');
const { sep } = path;
const glob = require('glob');

/**
 * 加载中间件
 * @param {*} app Elpis应用实例
 */
module.exports = (app) => {
    const middlewarePath = path.resolve(app.bisinessPath, `.${sep}middlewares`);
    const fileList = glob.sync(path.resolve(middlewarePath, `.${sep}**${sep}**.js`));
    /**
     * 中间件对象
     * 中间件对象的结构与中间件文件的目录结构相同
     * 例如：
     * 中间件文件：middlewares/logger.js
     * 中间件对象：middlewares.logger
     * 中间件文件：middlewares/logger/console.js
     * 中间件对象：middlewares.logger.console
     */
    const middlewares = {}
    fileList.forEach((file) => {
        let name = path.resolve(file)
        name = name.substring(name.lastIndexOf(`middlewares${sep}`) + `middlewares${sep}`.length, name.lastIndexOf('.'))
        name = name.replace(/[_-][a-z]/ig, (s) => s.substring(1).toUpperCase())

        let tempMiddleware = middlewares
        const names = name.split(sep);
        names.forEach((n, i) => {
            // 最后一个元素为文件名，加载中间件
            if (i == names.length - 1) {
                tempMiddleware[names[i]] = require(path.resolve(file))(app)
            } else {
                // 非最后一个元素为目录名，创建目录对象
                if (!tempMiddleware[names[i]]) {
                    tempMiddleware[names[i]] = {}
                }
                tempMiddleware = tempMiddleware[names[i]]
            }
        })
    });
    // 挂载中间件对象到应用实例
    app.middlewares = middlewares;
}